import path from "path";
import { Umzug, SequelizeStorage } from "umzug";
import { Sequelize } from "sequelize";
import { sequelize, User } from "./models";

/*
node migrate --help # show CLI help

node migrate up # apply migrations
node migrate down # revert the last migration
node migrate down --to 0 # revert all migrations
node migrate up --step 2 # run only two migrations

node migrate create --name my-migration.ts # create a new migration file 
 */

export const migrator = new Umzug({
    migrations: {
        glob: ["migrations/*.js", { cwd: path.resolve(__dirname, "..", "..") }],
    },
    // 一个可选的上下文对象，如果已定义，它将被传递给每个迁移函数
    context: sequelize,
    storage: new SequelizeStorage({
        sequelize,
        modelName: "User",
    }),

    logger: console,
});

// 导出由umzug公开的类型帮助器，它将正确地输入“context”参数
export type Migration = typeof migrator._types.migration;

(async () => {
    // 检查迁移，如果尚未应用，则运行它们。
    // 为了跟踪已执行的迁移，将自动创建一个名为 SequelizeMeta 的表(和sequelize模型),并对其进行解析。
    await migrator.up(); // up()方法用于应用迁移。默认情况下，运行所有挂起的迁移。
})();

migrator.runAsCLI();
